<template>
  <a-modal
    v-model="show"
    :centered="true"
    :maskClosable="false"
    width=70%
    :title="formName"
    ok-text="确认" cancel-text="取消"
    @cancel="onClose" @ok="handleSubmit">
    <!-- 表单区域 -->
    <fm-generate-antd-form
      :data="jsonData"
      :remote="remoteFuncs"
      :value="editData"
      :remote-option="dynamicData"
      ref="GenerateForm"
      v-if="visible"
    >
    </fm-generate-antd-form>
    <candidate-users ref="CandidateUsers" @setCandidateUser="setCandidateUser"></candidate-users>
  </a-modal>
</template>
<script>

import CandidateUsers from './CandidateUsers'

export default {
  name: 'ApplyForm',
  components: {CandidateUsers},
  props: {
    visible: {
      default: false
    },
    username: {
      require: true
    }
  },
  data () {
    return {
      candidateUsersParams: {
        sequenceId: '',
        candidateUser: ''
      },
      formName: '',
      processKey: '',
      jsonData: {},
      editData: {},
      remoteFuncs: {},
      dynamicData: {},
      applyData: {}
    }
  },
  computed: {
    show: {
      get: function () {
        return this.visible
      },
      set: function () {
      }
    }
  },
  methods: {
    onClose () {
      this.editData = {}
      this.$emit('close')
    },
    setFormParams(formJson, formTitle, processKey) {
      this.jsonData = JSON.parse(formJson)
      this.formName = formTitle
      this.processKey = processKey
    },
    setFormData(data) {
      console.log(data)
      this.editData = data
    },
    setCandidateUser (user, sequenceId) {
      this.candidateUsersParams.candidateUser = user
      this.launchProcess()
      this.$refs.CandidateUsers.closeModal()
    },
    handleSubmit () {
      this.$get('process/launch/candidateUsers?procDefKey=' + this.processKey).then((r) => {
        if (r.data.ifShowSetCandidateUser) {
          this.$refs.CandidateUsers.setUsers(r.data.userList)
          this.$refs.CandidateUsers.showModal()
        } else {
          this.launchProcess()
        }
      })
    },
    launchProcess () {
      this.loading = true
      this.$refs.GenerateForm.getData().then(data => {
        let formdata = JSON.stringify(data)
        this.$post('process/launch', {
          applicant: this.username,
          processDefinitionKey: this.processKey,
          flowData: formdata,
          nextAssignee: this.candidateUsersParams.candidateUser}).then((res) => {
          if (res.data.status) {
            this.loading = false
            this.$emit('success')
            this.editData = {}
          } else {
            this.$message.error(res.data.message)
          }
          this.loading = false
        })
      }).catch(e => {
        this.loading = false
      })
    }
  }
}
</script>
<style lang="scss">
  .dynamic-form-non-display {
    display: none;
  }
</style>
